<template>
  <div class="shop" v-loading="loading">
    <div class="store_line"></div>
    <div class="base_infoset">商品基础设置</div>
    <div class="triangle_right"></div>
    <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="关联分类:" prop="guanlian_cate">
        <el-select
          style="width:180px;"
          size="small"
          v-model="form.guanlian_cate"
          filterable
          class="select"
          placeholder="请选择关联的分类"
        >
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.cate_name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品标题:" prop="title">
        <el-input v-model="form.title" style="width:40%;" size="small"></el-input>
        <div class="base_title">原标题：{{yuan}}</div>
      </el-form-item>

      <el-form-item label="副标题:" prop="sub_title">
        <el-input v-model="form.sub_title" style="width:40%;" size="small"></el-input>
      </el-form-item>

      <el-form-item label="商品图片:" prop="img_arr">
        <div class="sku_pic">
          <div v-for="(item,index) in form.img_arr" :key="index" class="main_sku">
            <img
              style="width:160px;height:160px;"
              class="sku_pic_margin"
              :src="item? item : errorImg"
              alt
            />
            <p v-if="index ==0" class="main_img">商品主图</p>
            <p v-else class="other_img main_img">商品轮播图</p>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="展示排序:" prop="order">
        <el-input
          v-model="form.order_sort"
          type="number"
          style="width:40%;"
          size="small"
          placeholder="1~4999"
        ></el-input>
        <span class="sub_note">数值越大排序越靠前</span>
      </el-form-item>
    </el-form>

    <div class="add_info">
      <div class="store_line"></div>
      <div class="base_infoset base_addset">商品加润/抵扣设置</div>
      <div class="triangle_right add_right"></div>

      <el-form :model="addform" label-width="100px" class="demo-ruleForm">
        <el-form-item label="商品加润比:" prop="profit_set_rate">
          <el-input
            v-model="addform.profit_set_rate"
            type="number"
            style="width:40%;"
            size="small"
            @change="pricerateSet"
          >
            <p class="note_back" slot="suffix">%</p>
          </el-input>
          <span class="sub_note">加润比是在成本价的基础根据加润的比例售价，例如加润比100%，则售价是成本价的2倍</span>
        </el-form-item>

        <el-form-item label="红包抵扣:" prop="red_packet_discount_price">
          <div>
            <div>
              <el-radio v-model="add" :label="1">按比例</el-radio>
              <el-input
                v-model="addform.red_packet_discount_price"
                type="number"
                style="width:20%;"
                @change="profitChangeDiscount"
                size="small"
              >
                <p class="note_back" slot="suffix">%</p>
              </el-input>
              <span class="sub_note">
                设置红包可以抵扣的金额，基数是供货价格+运费，
                例如基数是60，比利是500%；
                红包抵扣值是300，如有小数点取整；
              </span>
            </div>
            <div>
              <el-radio v-model="add" :label="2">按固定</el-radio>
              <el-input
                v-model="addform.red_packet_discount_price2"
                type="number"
                style="width:20%;"
                @change="profitChangeDiscount"
                size="small"
              >
                <p class="note_back" slot="suffix">元</p>
              </el-input>
              <span class="sub_note">设置红包可以抵扣的金额，固定值设置300；红包抵扣值是300；</span>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="包邮件数设置:" prop="free_freight_num">
          <el-input
            v-model="addform.free_freight_num"
            type="number"
            style="width:40%;"
            size="small"
            @change="pricerateSet"
          >
            <p class="note_back" slot="suffix">件</p>
          </el-input>
          <span class="sub_note">设置包邮件数，是指n件起包邮，未达到包邮条件的需要增收运费，未设置默认为0，表示不包邮</span>
        </el-form-item>

        <el-form-item label="运费模板设置:">
          <el-select
            style="width:40%;"
            size="small"
            v-model="addform.freightTemplates"
            filterable
            class="select"
            placeholder="请选择运费模板设置"
          >
            <el-option
              v-for="item in freightTemplates"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <!-- 活动设置 -->
    <div class="add_info">
      <div class="store_line"></div>
      <div class="base_infoset base_addset">活动设置</div>
      <div class="triangle_right add_right"></div>
      <el-form ref="form" :model="activityform" label-width="100px">
        <el-form-item label="是否新人购:" prop="limit_user">
          <el-radio-group v-model="activityform.limit_user">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>

    <!-- 优惠券设置 -->
    <div class="add_info">
      <div class="store_line"></div>
      <div class="base_infoset base_addset">优惠券设置</div>
      <div class="triangle_right add_right"></div>
      <div class="couponWrap">
        <div class="couponTitle">优惠券选择：</div>
        <div class="couponContent" v-for="(item,index) in couponList" :key="index">
          <p>券面额：{{item.price}}</p>
          <p>有效期：{{item.use_end_time}} / {{item.use_start_time}}</p>
        </div>
      </div>
    </div>
    <!-- 商品参数设置 -->
    <div class="sku_info">
      <div class="store_line"></div>
      <div class="base_infoset">商品参数设置</div>
      <div class="triangle_right"></div>

      <div class="table">
        <el-table
          border
          :data="tableData"
          style="width:100%"
          max-height="680"
          :cell-style="tc"
          :header-cell-style="tccolor"
        >
          <el-table-column label="SKU编号" prop="sku_id"></el-table-column>
          <el-table-column v-for="(item,index) in attr_name_arr" :label="item" :key="index">
            <template slot-scope="scope">
              <p>{{scope.row.attr_value_arr[index]}}</p>
            </template>
          </el-table-column>
          <el-table-column label="商品库存" prop="stock"></el-table-column>
          <el-table-column label="虚拟销量" prop="fictitious_sale_count" width="140">
            <template slot-scope="scope">
              <!-- <div class="rectangle">{{scope.row.fictitious_sale_count}}</div> -->
              <el-input-number
                size="mini"
                style="width:100px;"
                v-model="scope.row.fictitious_sale_count"
                :min="0"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="库存预警" prop="warning_stock" width="140">
            <template slot-scope="scope">
              <el-input-number
                size="mini"
                style="width:100px;"
                v-model="scope.row.warning_stock"
                :min="0"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="供货成本价" prop="supply_price"></el-table-column>
          <el-table-column label="运费成本" prop="supply_freight_price"></el-table-column>
          <el-table-column label="* 销售价格" width="140">
            <template slot-scope="scope">
              <!-- <div class="rectangle">¥{{scope.row.sale_price}}</div> -->
              <el-input
                v-model="scope.row.sale_price"
                size="mini"
                style="width:100px"
                type="number"
                @change="saleprice(scope.row)"
              ></el-input>
            </template>
          </el-table-column>
          <!-- <el-table-column label="活动优惠价" width="140">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.price_act"
                size="mini"
                style="width:100px"
                type="number"
                @change="saleprice(scope.row)"
              ></el-input>
            </template>
          </el-table-column>-->
          <el-table-column label="* 红包抵扣" width="140">
            <template slot-scope="scope">
              <!-- <div class="rectangle">{{scope.row.red_packet_discount_price}}</div> -->
              <el-input
                v-model="scope.row.red_packet_discount_price"
                size="mini"
                style="width:100px"
                type="number"
                @change="discountprice(scope.row)"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="实付价">
            <template slot-scope="scope">{{scope.row.actual_price}}</template>
          </el-table-column>
          <el-table-column label="商品利润" prop="profit"></el-table-column>
          <el-table-column label="操作" fixed="right">
            <!--返回1说明该sku当前是展示的，0说明该sku当前是隐藏的-->
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="danager"
                v-if="scope.row.is_display==1"
                @click="hideSku(scope.row,1)"
              >隐藏</el-button>
              <el-button
                size="mini"
                type="danager"
                v-if="scope.row.is_display==0"
                @click="hideSku(scope.row,2)"
              >展示</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="certain_add">
      <el-button size="small" @click="cancelAdd">取消</el-button>
      <el-button type="primary" size="small" v-if="type==1 || type==3" @click="addShopToStore">保存入库</el-button>
      <el-button type="primary" size="small" v-if="type==2" @click="addShopToStore">保存修改</el-button>
    </div>
  </div>
</template>

<script>
import {
  supplyProductSkuList,
  supplyProductImgList,
  supplyproductCateList,
  freightTemplateList,
  selfproductDetail,
  selfproductUpdate,
  supplyYcProductDetail
} from "@/api/autarky";

export default {
  data() {
    return {
      add: "",
      type: 0,
      product_no: "",
      categoryList: [],
      freightTemplates: [],
      yuan: "",
      form: {
        guanlian_cate: "",
        title: "",
        sub_title: "",
        img_arr: [],
        order_sort: 0
      },
      addform: {
        profit_set_rate: 0,
        red_packet_discount_price: 0,
        red_packet_discount_price2: 0,
        red_packet_discount_price3: 0,
        freightTemplates: "",
        free_freight_num: 0
      },
      activityform: {
        limit_user: 0
      },
      couponList: [],
      //sku相关
      tableData: [],
      attr_name_arr: [],
      rules: {
        guanlian_cate: [
          { required: true, message: "请选择关联分类", trigger: "blur" }
        ],
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          { min: 1, max: 55, message: "长度不能少于一个字符", trigger: "blur" }
        ],
        // sub_title: [
        //     {required: true, message: '请输入副标题', trigger: 'blur'},
        //     {min: 1, max: 50, message: '长度不能少于一个字符', trigger: 'blur'}
        // ],
        img_arr: [
          { required: true, message: "请选择商品图片", trigger: "blur" }
        ],
        order_sort: [
          { required: true, message: "请选择展示排序", trigger: "blur" }
        ]
      },
      loading: false
    };
  },
  mounted() {
    this.type = this.$route.query.type;

    if(this.type == 3) {
      //来自于云仓选品
      this.product_no = this.$route.query.product_no;

      if(this.product_no) {
        this.getsupplyproductCateListData();
        this.listFreightTemplates();

        supplyYcProductDetail(this.product_no).then((res)=>{
          let data = res.data;

          this.form.title = data.title;
          this.form.img_arr = data.imgUrls.split(",");

          this.tableData = [];
          this.attr_name_arr = [];
          if(data.skuList && data.skuList.length > 0) {
            data.skuList.forEach((item)=>{
              this.attr_name_arr.push(item.attrName);
            })
          }
          if(data.skuInfo && data.skuInfo.length > 0) {
            data.skuInfo.forEach((item)=>{
              let v = item.value.split(",");
              this.tableData.push(
                {
                  sku_id: item.id,
                  attribute: item.attribute,
                  stock: item.inventory,
                  supply_price: item.wholesalePrice,
                  sale_price: item.salePrice,
                  supply_freight_price: data.freightPrice,
                  fictitious_sale_count: 0,
                  warning_stock: parseInt(item.inventory / 10),
                  red_packet_discount_price: 0,
                  attr_value_arr: v,
                  is_display: item.inventory > 0 ? 1 : 0,
                  actual_price: item.salePrice,
                  profit: (item.salePrice - item.wholesalePrice).toFixed(0),
                }
              )

            })
          }
          console.log(this.tableData)
        }).catch((err)=>{

        })
      }
    } else {
      this.product_no = this.$route.query.product_no;
      this.form.title = this.$route.query.title;
      this.yuan = this.form.title;
      if (this.product_no) {
        this.getsupplyproductCateListData();
        this.getselfproductDetailData();
        this.getsupplyProductImgListData();
        this.getsupplyProductSkuListData();
        this.listFreightTemplates();
      }
    }
  },
  methods: {
    //取消
    cancelAdd() {
      this.$router.push({ path: "./supplyChainStore" });
    },
    //保存入库
    addShopToStore() {
      this.getselfproductUpdateData();
    },
    //展示。。隐藏
    hideSku(skuInfo, type) {
      if (type == 1) {
        if (skuInfo) {
          skuInfo.is_display = 0;
        }
      } else {
        skuInfo.is_display = 1;
      }
    },
    profitChangeDiscount() {
      if (this.add == "") {
        this.$message.error("请选择抵扣方式");
        return;
      }
      // let a;
      if (this.add == 1) {
        if (this.tableData.length > 0) {
          this.tableData.map(obj => {
            let su = Number(obj.supply_price);
            let sf = Number(obj.supply_freight_price);
            this.addform.red_packet_discount_price3 =
              (this.addform.red_packet_discount_price / 100) * (su + sf);
            obj.red_packet_discount_price = this.addform.red_packet_discount_price3;
            obj.actual_price = (
              obj.sale_price - this.addform.red_packet_discount_price3
            ).toFixed(0);
            if (obj.actual_price < 0) {
              obj.actual_price = 0;
            }
            // obj.profit = (obj.actual_price - obj.supply_price).toFixed(0);
            obj.profit = this.getProfit(obj);
          });
        }
      } else {
        if (this.tableData.length > 0) {
          this.tableData.map(obj => {
            console.log(this.addform.red_packet_discount_price2);
            this.addform.red_packet_discount_price3 = Number(
              this.addform.red_packet_discount_price2
            );
            obj.red_packet_discount_price = this.addform.red_packet_discount_price2;
            obj.actual_price = (
              obj.sale_price - this.addform.red_packet_discount_price3
            ).toFixed(0);
            if (obj.actual_price < 0) {
              obj.actual_price = 0;
            }
            // obj.profit = (obj.actual_price - obj.supply_price).toFixed(0);
            obj.profit = this.getProfit(obj);
          });
        }
      }
    },
    getProfit(obj) {
      return (Number(obj.actual_price) + Number(obj.red_packet_discount_price) / 5.1 - Number(obj.supply_price) - Number(obj.supply_freight_price)).toFixed(2);
    },
    pricerateSet() {
      if (this.tableData.length > 0) {
        this.tableData.map(obj => {
          obj.sale_price = (
            obj.supply_price *
            (1 + this.addform.profit_set_rate / 100)
          ).toFixed(2);
          obj.actual_price = (
            obj.sale_price - obj.red_packet_discount_price
          ).toFixed(2);
          if (obj.actual_price < 0) {
            obj.actual_price = 0;
          }
          // obj.profit = (obj.actual_price - obj.supply_price).toFixed(2);
          obj.profit = this.getProfit(obj);
        });
      }
    },
    //red_packet_discount_price actual_price sale_price
    saleprice(data) {
      console.log(data);
      data.actual_price = (
        data.sale_price - data.red_packet_discount_price
      ).toFixed(2);
      if (data.actual_price < 0) {
        data.actual_price = 0;
      }
      // data.profit = (data.actual_price - data.supply_price).toFixed(2);
      data.profit = this.getProfit(data);
      // data.profit = (Number(data.actual_price) + Number(data.red_packet_discount_price) / 5.5 - Number(data.supply_price) - Number(data.supply_freight_price)).toFixed(2);
    },
    discountprice(data) {
      data.actual_price = (
        data.sale_price - data.red_packet_discount_price
      ).toFixed(2);
      if (data.actual_price < 0) {
        data.actual_price = 0;
      }

      console.log(data)
      data.profit = this.getProfit(data);
    },
    //获取商品详情
    async getselfproductDetailData() {
      let res = await selfproductDetail(this.product_no);
      if (res.code === 10000) {
        if (res.data.title) {
          this.form.title = res.data.title;
        }
        this.form.sub_title = res.data.sub_title;

        this.form.order_sort = res.data.order_sort;
        this.form.guanlian_cate = res.data.cate_id;
        this.addform.profit_set_rate = res.data.profit_set_rate;
        this.addform.red_packet_discount_price =
          res.data.red_packet_discount_price;
        this.addform.freightTemplates = res.data.freight_template_id;
        this.addform.free_freight_num = res.data.free_freight_num;
        this.couponList = res.data.coupon;
        this.activityform.limit_user = res.data.limit_user;
      } else {
        this.$message.error(res.message);
      }
    },
    //查看sku图片
    async getsupplyProductImgListData() {
      let res = await supplyProductImgList(this.product_no);
      if (res.code === 10000) {
        this.form.img_arr = res.data;
      } else {
        this.$message.error(res.message);
      }
    },
    async getsupplyProductSkuListData() {
      let res = await supplyProductSkuList(this.product_no);
      if (res.code === 10000) {
        this.attr_name_arr = res.data.attr_name_arr;
        this.tableData = res.data.list;
      } else {
        this.$message.error(res.error);
      }
    },
    //获取分类列表
    async getsupplyproductCateListData() {
      var url = "id=&is_enable=1&cate_name=";
      let res = await supplyproductCateList(url);
      if (res.code === 10000) {
        this.categoryList = res.data.data;
      } else {
        this.$message.error(res.message);
      }
    },

    //获取运费模板
    async listFreightTemplates() {
      let res = await freightTemplateList();
      if (res.code === 10000) {
        this.freightTemplates = res.data;
      } else {
        this.$message.error(res.message);
      }
    },

    //更新详情
    async getselfproductUpdateData() {
      if (!this.addform.freightTemplates) {
        this.$message.error("运费模版设置必选");
        return;
      }
      if (!this.addform.profit_set_rate) {
        this.addform.profit_set_rate = 0;
      }
      // let pic =0;
      // if (this.addform.red_packet_discount_price==0&&this.addform.red_packet_discount_price2!=0) {
      //     pic = this.addform.red_packet_discount_price2
      // }else if (this.addform.red_packet_discount_price!=0&&this.addform.red_packet_discount_price2==0) {
      //     pic = this.addform.red_packet_discount_price
      // }
      if (!this.addform.free_freight_num) {
        this.addform.free_freight_num = 0;
      }
      this.loading = true;
      var data = {
        cate_id: this.form.guanlian_cate,
        title: this.form.title,
        sub_title: this.form.sub_title,
        order_sort: this.form.order_sort,
        profit_set_rate: this.addform.profit_set_rate,
        // red_packet_discount_price: 10,
        freight_template_id: this.addform.freightTemplates,
        free_freight_num: this.addform.free_freight_num,
        limit_user: this.activityform.limit_user,
        type: this.type
      };
      if (this.tableData.length > 0) {
        //   this.tableData.forEach(function (obj, index) {
        //     var dic = {}
        //   Object.keys(obj).map(item => {

        //     var str = 'sku_list[' + index + '][' + item + ']'
        //     dic[str] = obj[item]
        //   })
        //   skuArr.push(dic)

        // })
        data["sku_list"] = JSON.stringify(this.tableData);
        console.log(data["sku_list"]);
      }
      console.log(data["sku_list"]);
      let res = await selfproductUpdate(this.product_no, data);
      if (res.code === 10000) {
        this.loading = false;
        this.$message.success(res.message);
        if (this.type == 1) {
          this.$router.push({
            path: "./addshopTostore"
          });
        } else if (this.type == 3) {
          this.$router.push({
            path: "./supplyYcChainStore"
          });
        } else {
          this.$router.push({
            path: "./localstore"
          });
        }
      } else {
        this.loading = false;
        this.$message.error(res.message);
      }
    },
    //获取商品图片
    getFile(file) {
      if (
        file.files &&
        file.files.length &&
        file.name == 'storeShop_pic_list"'
      ) {
        this.img_url = file.files.map(obj => obj.url);
      }
      console.log(this.img_url);
    },

    tc() {
      return "text-align:center; color:#333333; font-size:12px;";
    },
    tccolor() {
      return "text-align:center;background-color:#f5f5f5; font-size:14px;";
    }
  }
};
</script>

<style lang="scss" scoped>
.shop {
  position: relative;
  .store_line {
    background-color: #e5e5e5;
    height: 1px;
    margin-top: 20px;
    width: 100%;
  }
  .base_infoset {
    background-color: #f4222d;
    color: #ffffff;
    font-size: 18px;
    height: 30px;
    line-height: 30px;
    margin-left: 20px;
    padding: 0px 12px;
    width: 140px;
  }

  .base_addset {
    width: 180px;
  }
  .triangle_right {
    position: absolute;
    top: 1px;
    left: 160px;
    width: 0px;
    height: 0px;
    border: 15px solid transparent;
    border-left: 15px solid #f4222d;
  }

  .add_info {
    position: relative;
    .add_right {
      left: 200px;
    }
  }
  .sku_info {
    position: relative;
    .table {
      padding: 0 20px;
      margin-top: 20px;

      .rectangle {
        border: 1px solid #e5e5e5;
      }
    }
  }

  .demo-ruleForm {
    position: relative;
    margin: 15px 0px;
    .base_title {
      font-size: 12px;
      color: #333333;
    }
    .sub_note {
      margin-left: 12px;
      font-size: 14px;
      color: #666666;
    }
  }
  .certain_add {
    text-align: center;
    margin-top: 20px;
  }
  .sku_pic {
    padding: 12px 20px;
    .sku_pic_margin {
      margin: 12px 12px;
    }
    .main_sku {
      position: relative;
      float: left;
    }
    .main_img {
      position: absolute;
      bottom: 0;
      left: 12px;
      background-color: #f5f5f5;
      color: #f4222d;
      text-align: center;
      font-size: 14px;
      line-height: 30px;
      height: 30px;
      width: 160px;
    }
    .other_img {
      color: rgb(71, 255, 47);
    }
  }
}
.couponWrap {
  display: flex;
}
.couponTitle {
  margin-left: 15px;
  margin-top: 10px;
}
.couponContent {
  margin-top: 10px;
  width: 250px;
  border: 1px solid #999;
  border-radius: 5px;
  margin-right: 10px;
  padding: 5px;
}
</style>
